<template>
    <div style="padding: 2%;">

        <a-card>
            <!-- 顶栏 -->
            <template #title>
                <div style="display: flex;align-items:center;">
                    <span style="font: 700 16px 微软雅黑">漫画类型表</span>

                    <div style="flex-grow: 1;" />

                    <a-button type="primary" :icon="h(PlusOutlined)" @click="isInsert = true">新增数据</a-button>
                </div>

            </template>

            <!-- 查询表单 -->
            <a-form ref="formRef" name="advanced_search" style="margin: 0 0px 20px 10px;align-items: center;"
                :model="searchForm" layout="inline">


                <a-form-item name="name" label="名称">
                    <a-input v-model:value="searchForm.name" placeholder="模糊查询：名称" />
                </a-form-item>


                <a-form-item class="m-left-auto">
                    <a-button type="primary" @click="getDataSource" :loading="loading">查询</a-button>
                    <a-button style="margin: 0 8px" @click="clearSearchForm">清空</a-button>
                </a-form-item>


            </a-form>

            <a-divider></a-divider>

            <!-- 数据表 -->
            <a-table :columns="columns" :data-source="dataSource" size="middle" :pagination="pagination" bordered>

                <template #bodyCell="{ column, text, record }">

                    <template v-if="column.dataType === 'date'">
                        {{ new Date(text).toLocaleString() }}
                    </template>

                    <template v-if="column.key === 'operation'">
                        <a-button type="link"
                            @click="isUpdate = true; updateFrom = JSON.parse(JSON.stringify(record))">修改</a-button>
                        <a-popconfirm title="不可逆操作，请谨慎执行" ok-text="执行" cancel-text="取消"
                            @confirm="deleteSubmit(record.ctid)">
                            <a-button type="link" danger>删除</a-button>
                        </a-popconfirm>

                    </template>

                </template>

            </a-table>

        </a-card>

        <!-- 新增弹框 -->
        <a-modal v-model:open="isInsert" ref="insertFormRef" title="新增" :keyboard="false" :maskClosable="false">
            <a-form :model="formState" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" @finish="insertSubmit"
                @finishFailed="() => message.error('请检查填写是否完整')">

                <a-form-item label="类型名称" name="name" :rules="[{ required: true, message: '必填项' }]">
                    <a-input v-model:value="formState.name" />
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" html-type="submit">提交</a-button>
                </a-form-item>

            </a-form>
            <template #footer>
                <a-button @click="isInsert = false">关闭</a-button>
            </template>
        </a-modal>

        <!-- 修改弹框 -->
        <a-modal v-model:open="isUpdate" ref="updateFromRef" title="修改" :keyboard="false" :maskClosable="false">
            <a-form :model="updateFrom" :label-col="{ span: 7 }" :wrapper-col="{ span: 12 }" @finish="updateSubmit"
                @finishFailed="() => message.error('请检查填写是否完整')">

                <a-form-item label="ID" name="id">
                    <a-tooltip placement="top" title="唯一键不可修改">
                        <a-input v-model:value="updateFrom.ctid" disabled />
                    </a-tooltip>
                </a-form-item>

                <a-form-item label="类型名称" name="name" :rules="[{ required: true, message: '必填项' }]">
                    <a-input v-model:value="updateFrom.name" />
                </a-form-item>

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" html-type="submit" :loading="loading">提交</a-button>
                </a-form-item>

            </a-form>
            <template #footer>
                <a-button @click="isUpdate = false">关闭</a-button>
            </template>
        </a-modal>


    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, h } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { HttpStatusCode } from 'axios';
import { api } from '@/myAxios';


const dataSource = ref([
    {
        "ctid": -1,
        "name": "测试",
        "createTime": "2024-05-09T11:22:17",
        "updateTime": "2024-05-09T11:22:17",
        "state": 1
    },
])

const columns = [
    {
        title: "ID",
        dataIndex: 'ctid',
        width: 20,
        align: 'center',
    },
    {
        title: "类型名称",
        dataIndex: 'name',
        width: 80,
    },
    {
        title: "入库时间",
        dataIndex: 'createTime',
        width: 120,
        dataType: 'date',
        resizable: true,
    },
    {
        title: "更新时间",
        dataIndex: 'updateTime',
        width: 120,
        dataType: 'date',
        resizable: true,
    },
    {
        key: 'operation',
        title: "操作",
        fixed: 'right',
        width: 100,
    },
]

const pagination = {
    size: 'large',
    defaultPageSize: 5,
    pageSizeOptions: ['5', '10', '15', '20'],
    showSizeChanger: true,
    showQuickJumper: true,
}

const searchForm = ref({
    name: null,
})
const clearSearchForm = () => {
    searchForm.value = {
        name: null,
    }
}

const loading = ref(false);

const isInsert = ref(false);
const formState = ref({
    name: '',
})


const isUpdate = ref(false);
const updateFrom = ref({
    ctid: -1,
    name: '',
})

onMounted(
    () => {
        getDataSource()
    }
)

const getDataSource = async () => {
    loading.value = true;
    try {
        const params = {
            name: searchForm.value.name,
        }

        const result = await api.get('/cartoonType', { params })

        if (result.data.code === HttpStatusCode.Ok) {
            dataSource.value = result.data.data;
        }
    } catch (err) {
        console.log(err);
        message.error('获取信息失败！！');
    } finally {
        loading.value = false;
    }
}

const insertSubmit = async () => {

    loading.value = true;
    try {
        const data = {
            name: formState.value.name,
        }
        const result = await api.post('/cartoonType', data);

        if (result.data.code === HttpStatusCode.Ok) {
            isInsert.value = false;
            console.log(result.data);
            message.success('新增数据成功：' + result.data.data);
            getDataSource()
            formState.value.name = ''
        } else {
            if (result.data.code === 409 && result.data.msg === 'Duplicate_Key') {
                message.warning("新增数据失败：'" + data.name + "' 已被使用！！！")
            } else if (result.data.code === HttpStatusCode.Unauthorized) {
                message.error('接口权限不足？建议重新登录！！！');
            }

        }

    } catch (err) {
        console.log(err);
        message.error('访问接口失败！！');
    } finally {
        loading.value = false;
    }
}

const updateSubmit = async () => {

    loading.value = true;
    try {
        const data = {
            ctid: updateFrom.value.ctid,
            name: updateFrom.value.name,
        }

        const result = await api.put('/cartoonType', data);

        if (result.data.code === HttpStatusCode.Ok) {
            isUpdate.value = false;
            getDataSource()
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        }


    } catch (err) {
        console.log(err);
        message.error('访问接口失败！！');
    } finally {
        loading.value = false;
    }
}

const deleteSubmit = async (id: number) => {
    try {
        const data: number[] = [];
        data.push(id);

        const result = await api.delete('/cartoonType/' + data);

        if (result.data.code === HttpStatusCode.Ok) {
            getDataSource()
        } else if (result.data.code === HttpStatusCode.Unauthorized) {
            message.error('接口权限不足？建议重新登录！！！');
        }


    } catch (err) {
        console.log(err);
        message.error('获取信息失败！！');
    }
}


</script>